﻿using UnityEngine;
using System.Security.Cryptography;
using System.Text;
using System.IO;

public class CryptographHelper
{
    public static string CrypfString(string source, string key = "")
    {
        byte[] inputs = Encoding.UTF8.GetBytes(source);
        byte[] hash = inputs;//Md5Instance.ComputeHash(inputs);
        string outStr = System.Convert.ToBase64String(hash);
        outStr = outStr.Replace("=", "");
        outStr = outStr.Replace(@"/", "-");
        return outStr;
    }

    // 加密
    public static byte[] Encrypt(byte[] bytes, byte[] Key, byte[] IV)
    {
        byte[] encrypted;
        using (RijndaelManaged manager = new RijndaelManaged())
        {
            manager.Key = Key;
            manager.IV = IV;

            ICryptoTransform encryptor = manager.CreateEncryptor(manager.Key, manager.IV);
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    csEncrypt.Write(bytes, 0, bytes.Length);
                    csEncrypt.FlushFinalBlock();
                    encrypted = msEncrypt.ToArray();
                }
            }
        }

        return encrypted;
    }

    // 解密
    public static byte[] Decrypt(byte[] bytes, byte[] Key, byte[] IV)
    {
        byte[] original = null;

        using (RijndaelManaged manager = new RijndaelManaged())
        {
            manager.Key = Key;
            manager.IV = IV;

            using (MemoryStream msDecrypt = new MemoryStream(bytes))
            {
                ICryptoTransform decryptor = manager.CreateDecryptor(manager.Key, manager.IV);
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (MemoryStream originalMemory = new MemoryStream())
                    {
                        byte[] Buffer = new byte[1024];
                        int readBytes = 0;
                        while ((readBytes = csDecrypt.Read(Buffer, 0, Buffer.Length)) > 0)
                        {
                            originalMemory.Write(Buffer, 0, readBytes);
                        }

                        original = originalMemory.ToArray();
                    }
                }
            }

        }

        return original;
    }
}